<template>
  <div v-loading="loading" class="classify-con">
    <el-scrollbar ref="classifyScrollbar" class="classify-scrollbar">

      <div v-for="(item, index) in formatData" :key="index" class="classify-item">
        <div class="item-info">
          <el-col :span="16">
            <el-input
              v-model.trim="item.winningName"
              :disabled="!item._edit"
              placeholder="请输入奖项名称"
              style="width: 90%; margin-right: 10px;"
            />
          </el-col>
          <el-col :span="6">
            <el-switch
              v-model="item.status"
              active-value="ZT01"
              inactive-value="ZT02"
              @change="changeStatus(item)"
            />
          </el-col>
          <el-col :span="4">
            <el-button
              :disabled="item.isFirst"
              type="text"
              @click="move(item, 'SY')"
            >上移
            </el-button>
            <el-button
              :disabled="item.isLast"
              type="text"
              @click="move(item, 'XY')"
            >下移
            </el-button>
          </el-col>

        </div>
        <div class="item-btn">
          <el-button v-if="item._edit" size="mini" type="text" @click="classifyUpdateSub(item, index)">保存</el-button>
          <el-button v-else size="mini" type="text" @click="classifyUpdate(item, index)">编辑</el-button>
          <el-button size="mini" type="text" @click="classifyDelete(item, index)">删除</el-button>
        </div>
      </div>
      <div class="classify-add" @click="addClassify">+点击此处添加奖项</div>
    </el-scrollbar>
  </div>
</template>
<script>
import { fetchList, insert, update, del, move, updateStatus } from './api'
import permission from '@/directive/permission/index.js' // 权限判断指令
import Vue from 'vue'
import { queryAwards } from '@/views/activity/zjhd/api/winner'

export default {
  name: 'Classify',
  directives: { permission },
  props: {
    parentref: {
      type: Boolean,
      default: false
    },
    permissionInsert: {
      type: String,
      default: ''
    },
    permissionUpdate: {
      type: String,
      default: ''
    },
    permissionDelete: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      data: []
    }
  },
  computed: {
    formatData() {
      let tmp
      if (!Array.isArray(this.data)) {
        tmp = [this.data]
      } else {
        tmp = this.data
      }
      Array.from(tmp).forEach(item => {
        if (item._edit === undefined) {
          Vue.set(item, '_edit', false)
        }
      })
      return tmp
    }
  },
  created() {
    this.queryClassify()
  },
  methods: {

    /**
     * 切换编辑状态
     */
    toggleEdit(index) {
      const record = this.formatData[index]
      record._edit = !record._edit
    },

    /**
     * 查询奖项列表
     */
    queryClassify() {
      this.loading = true
      return new Promise((resolve, reject) => {
        fetchList({ dataId: this.$route.query.ai, dataType: 'ZJHD' }).then(response => {
          this.data = this.initData(response.data.data)
          this.loading = false
          resolve(response.data.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     * 递归增加是否可以上移下移标识
     * @param data
     * @returns {*}
     */
    initData(data, level = 1) {
      data.forEach((item, index) => {
        item['isFirst'] = false
        item['isLast'] = false
        item['isEdit'] = false
        if (index === 0) {
          item['isFirst'] = true
        }
        if (index === data.length - 1) {
          item['isLast'] = true
        }
        item['level'] = level
        if (item.children && item.children.length > 0) {
          return this.initData(item.children, level + 1)
        }
      })
      return data
    },
    /**
     * 切换启用禁用状态
     */
    changeStatus(row) {
      if (!row.id) {
        return
      }
      if (!row.isEdit) {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return new Promise((resolve, reject) => {
          updateStatus({ id: row.id, status: row.status }).then(() => {
            this.$message({
              message: '处理成功',
              type: 'success',
              duration: 2000
            })
            loading.close()
            this.refresh()
          }).catch(error => {
            loading.close()
            this.refresh()
            reject(error)
          })
        })
      }
    },
    /**
     * 奖项移动
     */
    move(row, dir) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return new Promise((resolve, reject) => {
        move({ id: row.id, msg: dir }).then(() => {
          this.$message({
            message: '处理成功',
            type: 'success',
            duration: 2000
          })
          loading.close()
          this.refresh()
        }).catch(error => {
          loading.close()
          this.refresh()
          reject(error)
        })
      })
    },
    /**
     * 添加
     */
    addClassify() {
      this.temp = {
        id: '',
        dataId: this.$route.query.ai,
        dataType: 'ZJHD',
        winningName: '',
        status: 'ZT01',
        _edit: true
      }
      this.data.push(this.temp)
      if (this.$refs['classifyScrollbar'].wrap.scrollHeight > 400) {
        this.$refs['classifyScrollbar'].wrap.style.height = 400
      }
      this.$nextTick(() => {
        this.$refs['classifyScrollbar'].wrap.scrollTop = this.$refs['classifyScrollbar'].wrap.scrollHeight
      })
    },

    /**
     * 编辑
     */
    classifyUpdate(item, index) {
      this.toggleEdit(index)
    },

    /**
     * 编辑提交
     */
    classifyUpdateSub(item, index) {
      if (item.winningName.trim() !== '') {
        this.loading = true
        if (item._edit) {
          delete item._edit
        }
        if (item.bid) {
          delete item.bid
        }
        return new Promise((resolve, reject) => {
          if (item.id === '') {
            insert(item).then(() => {
              this.loading = false
              this.$message({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              this.refresh()
            }).catch(error => {
              this.loading = false
              reject(error)
            })
          } else {
            update(item).then(() => {
              this.loading = false
              this.$message({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.refresh()
            }).catch(error => {
              this.refresh()
              this.loading = false
              reject(error)
            })
          }
        })
      } else {
        this.$message({
          message: '请输入奖项名称',
          type: 'warning'
        })
      }
    },

    /**
     * 删除
     */
    classifyDelete(item, index) {
      this.$confirm('此操作将永久删除该奖项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (item.id && item.id !== '') {
          this.deleteclassify(item.id)
        } else {
          this.data.splice(index, 1)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    /**
     * 删除提交
     */
    deleteclassify(id) {
      this.loading = true
      return new Promise((resolve, reject) => {
        del({ id: id }).then(() => {
          this.loading = false
          this.$message({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.refresh()
        }).catch(error => {
          this.loading = false
          reject(error)
        })
      })
    },

    /**
     * 更新
     */
    refresh() {
      this.queryClassify().then((res) => {
        if (this.parentref) {
          this.$emit('onrefresh', res)
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.classify-con {
  position: relative;

  .classify-scrollbar {
    width: 100%;
    height: 100%;
    overflow: hidden;

    .el-scrollbar__wrap {
      max-height: 400px;
      margin-bottom: 0 !important;
      overflow-x: hidden;
    }

    .el-scrollbar__view {
      margin: 10px;
      overflow: hidden;
    }
  }

  .classify-add {
    height: 40px;
    line-height: 40px;
    border: 1px dotted rgba(226, 227, 232, 1);
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(254, 90, 97, 1);
    text-align: center;
    cursor: pointer;
    margin-top: 10px;

    &:hover {
      border: 1px dotted #fe5a61;
    }
  }

  .classify-item {
    width: 100%;
    display: flex;
    align-items: center;
    margin-top: 10px;

    .item-info {
      flex: 1;
      display: flex;
      align-items: center;

      .sort {
        margin-left: 20px;
        color: #c0c4cc;
        display: inline-block;
        font-size: 14px;
        vertical-align: baseline;
        width: 15%;
        text-align: center;
      }
    }

    .item-btn {
      margin-left: 20px;
    }
  }
}
</style>
